package com.lxg.security.filter;

import com.lxg.security.exception.KaptchaNoMatchException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 陆小根
 * date: 2022/04/25
 * Description:
 * 自定义验证码的filter
 */

public class KaptchaFilter extends UsernamePasswordAuthenticationFilter {

  private static final String FORM_KAPTCHA_KEY = "kaptcha";

  private String kaptchaParameter = FORM_KAPTCHA_KEY;

  public String getKaptchaParameter() {
    return kaptchaParameter;
  }

  public void setKaptchaParameter(String kaptchaParameter) {
    this.kaptchaParameter = kaptchaParameter;
  }

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (!request.getMethod().equals("POST")) {
      throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }
    // 1.从请求中获取验证码
    String verifyCode = request.getParameter(getKaptchaParameter());
    // 2.与 session 中的验证码进行比较
    String sessionVerifyCode = (String) request.getSession().getAttribute("kaptcha");
    if (!ObjectUtils.isEmpty(sessionVerifyCode) && !ObjectUtils.isEmpty(verifyCode) &&
            verifyCode.equalsIgnoreCase(sessionVerifyCode)) {
      return super.attemptAuthentication(request, response);
    }
    throw new KaptchaNoMatchException("验证码不匹配!");
  }
}
